package com.css.fxfzysx.modules.lifeline.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.css.fxfzysx.base.response.RestResponse;
import com.css.fxfzysx.constants.FxfzConstants;
import com.css.fxfzysx.constants.YNEnum;
import com.css.fxfzysx.modules.cztDataMange.constans.RedisKeyConstants;
import com.css.fxfzysx.modules.cztDataMange.entity.CbcbDetailEntity;
import com.css.fxfzysx.modules.cztDataMange.entity.CbcbInfoEntity;
import com.css.fxfzysx.modules.cztDataMange.service.impl.BacInformationServiceImpl;
import com.css.fxfzysx.modules.cztDataMange.utils.GenerationNumberUtil;
import com.css.fxfzysx.modules.cztDataMange.vo.RcpExcelSheet1Vo;
import com.css.fxfzysx.modules.cztDataMange.vo.RcpExcelSheet2Vo;
import com.css.fxfzysx.modules.cztDataMange.vo.RcpExcelSheet3Vo;
import com.css.fxfzysx.modules.cztDataMange.vo.RcpExcelSheet4Vo;
import com.css.fxfzysx.modules.lifeline.constants.TableNameConstants;
import com.css.fxfzysx.modules.lifeline.entity.newEntity.*;
import com.css.fxfzysx.modules.lifeline.param.ImportHubBuildingParam;
import com.css.fxfzysx.modules.lifeline.repository.HubBuildingRepository;
import com.css.fxfzysx.modules.lifeline.repository.LifelineEngineeringRepository;
import com.css.fxfzysx.modules.lifeline.service.HubBuildingService;
import com.css.fxfzysx.modules.lifeline.utils.VersionCodeUtils;
import com.css.fxfzysx.modules.lifeline.vo.*;
import com.css.fxfzysx.modules.vabStructure.constans.BuildingRoofEnum;
import com.css.fxfzysx.modules.vabStructure.constans.BuildingSeismicResistanceEnum;
import com.css.fxfzysx.modules.vabStructure.entity.CztCrsMatrixCalResult;
import com.css.fxfzysx.modules.vabStructure.service.SrcAnalyseService;
import com.css.fxfzysx.modules.vaolEngineering.utils.MainTableUtils;
import com.css.fxfzysx.util.*;
import com.css.fxfzysx.util.hypergraph.service.HypergraphService;
import com.css.fxfzysx.web.PlatformSessionContext;
import com.css.fxfzysx.zcpt.sys.entity.SUser;
import com.css.fxfzysx.zcpt.sys.service.SUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class HubBuildingServiceImpl implements HubBuildingService {

    @Autowired
    private HubBuildingRepository hubBuildingRepository;

    @Autowired
    private SrcAnalyseService srcAnalyseService;

    @Autowired
    private MainTableUtils mainTableUtils;

    @Autowired
    private LifelineEngineeringRepository lifelineEngineeringRepository;

    @Autowired
    private VersionCodeUtils versionCodeUtils;

    @Autowired
    private SUserService userService;

    @Autowired
    private GenerationNumberUtil generationNumberUtil;

    @Autowired
    private BacInformationServiceImpl bacInformationService;

    @Autowired
    private HypergraphService hypergraphService;

    @Override
    public RestResponse importHubBuilding(MultipartFile file, ImportHubBuildingParam param) throws Exception {
        log.info("userId:{}",PlatformSessionContext.getUserID());
        Integer type = param.getType();
        Workbook workBook = null;
        String fileName = FileUtil.getPrefix(file.getOriginalFilename());
        try {
            workBook = PoiExcelUtil.getWorkBook(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        List<Map> mapList = new ArrayList<>();

        List sheet1List = new ArrayList<>();
        String versionId = "";

        //保存版本信息
        if (param.getCover() == 1) {
            versionId = updateVersionInfo(param, fileName);
            //删除主表数据
            lifelineEngineeringRepository.deleteMainByVersionId(versionId);
            //删除历史的数据
            lifelineEngineeringRepository.deleteOldVersionData(versionId, type,null);
            //删除钢混数据
            lifelineEngineeringRepository.deleteByVersionId(versionId);
            //删除砖混数据
            lifelineEngineeringRepository.deleteZhByVersionId(versionId);
        } else {
            versionId = saveVersionInfo(param, fileName);
        }

        Map<String, JSONObject> map = null;

        ArrayList<String> structureTypeList = new ArrayList<>();

        for (int numSheet = 0; numSheet < workBook.getNumberOfSheets(); numSheet++) {
            if (numSheet == 0) {
                if (type == 11) {
                    ExcelResult excelResult = ExcelReaderUtil.readExcelBean(file.getInputStream(), ImportWpRoomVo.class, 3, 0);
                    sheet1List = excelResult.getData();
                } else if (type == 12) {
                    ExcelResult excelResult = ExcelReaderUtil.readExcelBean(file.getInputStream(), ImportPowerhouseVo.class, 3, 0);
                    sheet1List = excelResult.getData();
                } else if (type == 13) {
                    ExcelResult excelResult = ExcelReaderUtil.readExcelBean(file.getInputStream(), ImportBaseStationVo.class, 3, 0);
                    sheet1List = excelResult.getData();
                } else if (type == 14) {
                    ExcelResult excelResult = ExcelReaderUtil.readExcelBean(file.getInputStream(), ImportGasVo.class, 3, 0);
                    sheet1List = excelResult.getData();
                }
                sheet1List.forEach(it -> {
                    JSONObject entity = JSONObject.parseObject(JSONObject.toJSONString(it));
                    structureTypeList.add(entity.get("structureType").toString());
                });
            }

            if (structureTypeList.toString().contains("砖")) {
                if (numSheet == 1) {
                    RestResponse restResponse = brickConcreteCalculation(file.getInputStream());
                    if (restResponse.getCode() != 200) {
                        return RestResponse.fail(restResponse.getMessage());
                    }
                    map = (Map<String, JSONObject>) restResponse.getData();
                }
            }
            if (structureTypeList.toString().contains("钢")) {
                if (numSheet == 2) {
                    ExcelResult excelResult = ExcelReaderUtil.readExcelBean(file.getInputStream(), ImportExcelSheet1Vo.class, 3, numSheet);
                    List<ImportExcelSheet1Vo> list = excelResult.getData();
                    if (PlatformObjectUtils.isNotEmpty(list)) {
                        ArrayList<RcpExcelSheet1Vo> sheetList = new ArrayList<>();
                        list.forEach(it -> {
                            RcpExcelSheet1Vo vo = new RcpExcelSheet1Vo();
                            BeanUtils.copyProperties(it, vo);
                            sheetList.add(vo);
                        });
                        Map<String, List<RcpExcelSheet1Vo>> sheet1Map = sheetList.stream().collect(Collectors.groupingBy(RcpExcelSheet1Vo::getNumType));
                        mapList.add(sheet1Map);
                    }
                }
                if (numSheet == 3) {
                    ExcelResult excelResult = ExcelReaderUtil.readExcelBean(file.getInputStream(), RcpExcelSheet2Vo.class, 4, numSheet);
                    List<RcpExcelSheet2Vo> list = excelResult.getData();
                    if (PlatformObjectUtils.isNotEmpty(list)) {
                        Map<String, List<RcpExcelSheet2Vo>> sheet2Map = list.stream().collect(Collectors.groupingBy(RcpExcelSheet2Vo::getNumType));
                        mapList.add(sheet2Map);
                    }
                }
                if (numSheet == 4) {
                    ExcelResult excelResult = ExcelReaderUtil.readExcelBean(file.getInputStream(), RcpExcelSheet3Vo.class, 3, numSheet);
                    List<RcpExcelSheet3Vo> list = excelResult.getData();
                    if (PlatformObjectUtils.isNotEmpty(list)) {
                        Map<String, List<RcpExcelSheet3Vo>> sheet3Map = list.stream().collect(Collectors.groupingBy(RcpExcelSheet3Vo::getNumType));
                        mapList.add(sheet3Map);
                    }
                }
                if (numSheet == 5) {
                    ExcelResult excelResult = ExcelReaderUtil.readExcelBean(file.getInputStream(), RcpExcelSheet4Vo.class, 3, numSheet);
                    List<RcpExcelSheet4Vo> list = excelResult.getData();
                    if (PlatformObjectUtils.isNotEmpty(list)) {
                        Map<String, List<RcpExcelSheet4Vo>> sheet4Map = list.stream().collect(Collectors.groupingBy(RcpExcelSheet4Vo::getNumType));
                        mapList.add(sheet4Map);
                    }
                }
            }
        }

        for (Object it : sheet1List) {
            if (type == 11) {
                String id = UUIDGenerator.getUUID();
                ImportWpRoomVo data = (ImportWpRoomVo) it;
                List<String> list = null;
                if (data.getStructureType().equals("钢筋混凝土框架结构")) {
                    if (PlatformObjectUtils.isNotEmpty(mapList)) {
                        List<Map> newMapList = calculationParameters(mapList, data.getNumType(), data.getStructureType(),id,versionId);
                        RestResponse res = steelConcreteCalculation(newMapList);
                        if(res.getCode() == 200){
                            list = (List<String>) res.getData();
                        }else {
                            return RestResponse.fail(res.getMessage());
                        }
                    }
                } else {
                    if (PlatformObjectUtils.isNotEmpty(map)) {
                        Map<String, JSONObject> newMap = calculationZhParameters(map, data.getNumType());
                        if(PlatformObjectUtils.isNotEmpty(newMap.get(data.getNumType()))){
                            list = bacInformationService.countPobStructure(newMap,id,versionId);
                        }else {
                            throw new RuntimeException("导入失败，请检查模板内容的正确性");
                        }
                    }
                }
                saveMainTable(versionId, FxfzConstants.CZT_SMX_SCBF, id);
                SmxWaterRoomEntity entity = waterRoomToEntity(data, versionId, id, list);
                hubBuildingRepository.saveWpRoom(entity);
            } else if (type == 12) {
                List<String> list = null;
                String id = UUIDGenerator.getUUID();
                ImportPowerhouseVo data = (ImportPowerhouseVo) it;
                if (data.getStructureType().equals("钢混结构")) {
                    if (PlatformObjectUtils.isNotEmpty(mapList)) {
                        List<Map> newMapList = calculationParameters(mapList, data.getNumType(), data.getStructureType(),id,versionId);
                        RestResponse res = steelConcreteCalculation(newMapList);
                        if(res.getCode() == 200){
                            list = (List<String>) res.getData();
                        }else {
                            return RestResponse.fail(res.getMessage());
                        }
                    }
                } else {
                    if (PlatformObjectUtils.isNotEmpty(map)) {
                        Map<String, JSONObject> newMap = calculationZhParameters(map, data.getNumType());
                        if(PlatformObjectUtils.isNotEmpty(newMap.get(data.getNumType()))){
                            list = bacInformationService.countPobStructure(newMap,id,versionId);
                        }else {
                            throw new RuntimeException("导入失败，请检查模板内容的正确性");
                        }
                    }
                }
                SmxPowerhouseEntity entity = powerhouseToEntity(data, versionId, id, list);
                hubBuildingRepository.savePowerhouse(entity);
                saveMainTable(versionId, FxfzConstants.CZT_SMX_ZYFD, id);
            } else if (type == 13) {
                List<String> list = null;
                String id = UUIDGenerator.getUUID();
                ImportBaseStationVo data = (ImportBaseStationVo) it;
                if (data.getStructureType().contains("钢筋混凝土")) {
                    if (PlatformObjectUtils.isNotEmpty(mapList)) {
                        List<Map> newMapList = calculationParameters(mapList, data.getNumType(), data.getStructureType(),id,versionId);
                        RestResponse res = steelConcreteCalculation(newMapList);
                        if(res.getCode() == 200){
                            list = (List<String>) res.getData();
                        }else {
                            return RestResponse.fail(res.getMessage());
                        }
                    }
                } else {
                    if (PlatformObjectUtils.isNotEmpty(map)) {
                        Map<String, JSONObject> newMap = calculationZhParameters(map, data.getNumType());
                        if(PlatformObjectUtils.isNotEmpty(newMap.get(data.getNumType()))){
                            list = bacInformationService.countPobStructure(newMap,id,versionId);
                        }else {
                            throw new RuntimeException("导入失败，请检查模板内容的正确性");
                        }
                    }
                }
                SmxBaseStationEntity entity = baseStationToEntity(data, versionId, id, list);
                hubBuildingRepository.saveBaseStation(entity);
                saveMainTable(versionId, FxfzConstants.CZT_SMX_JZ, id);
            } else if (type == 14) {
                List<String> list = null;
                String id = UUIDGenerator.getUUID();
                ImportGasVo data = (ImportGasVo) it;
                if (data.getStructureType().contains("钢混结构")) {
                    if (PlatformObjectUtils.isNotEmpty(mapList)) {
                        List<Map> newMapList = calculationParameters(mapList, data.getNumType(), data.getStructureType(),id,versionId);
                        RestResponse res = steelConcreteCalculation(newMapList);
                        if(res.getCode() == 200){
                            list = (List<String>) res.getData();
                        }else {
                            return RestResponse.fail(res.getMessage());
                        }
                    }
                } else {
                    if (PlatformObjectUtils.isNotEmpty(map)) {
                        Map<String, JSONObject> newMap = calculationZhParameters(map, data.getNumType());
                        if(PlatformObjectUtils.isNotEmpty(newMap.get(data.getNumType()))){
                            list = bacInformationService.countPobStructure(newMap,id,versionId);
                        }else {
                            throw new RuntimeException("导入失败，请检查模板内容的正确性");
                        }
                    }
                }
                SmxGasStoreEntity entity = gasStoreToEntity(data, versionId, id, list);
                hubBuildingRepository.saveGasStore(entity);
                saveMainTable(versionId, FxfzConstants.CZT_SMX_RQMZ, id);
            }
        }
        hypergraphService.getWorkspaceReload(TableNameConstants.getMainConstant(type));
        return RestResponse.succeed("导入成功!");
    }


    /**
     * 处理年代数据
     */
    private String handleYear(String year){
        int i = Integer.parseInt(year);
        if(i<1977){
            return "1978年以前";
        }else if(i>1977 && i<1988){
            return "1988-1989年";
        }else if(i>1988 && i<2000){
            return "1989-2001年";
        }else if(i>2000 && i<2009){
            return "2001-2010年";
        }else if(i>2009 && i<2015){
            return "2010-2016年";
        }else if(i>2015){
            return "2016年以后";
        }
        return "";
    }

    /**
     * 组装钢筋混凝土计算数据,每次返回一个建筑物序号的数据
     * @return
     */
    private Map<String,JSONObject> calculationZhParameters(Map<String, JSONObject> map,String numType){
        Map<String, JSONObject> newMap = new HashMap<>();
        JSONObject jsonObject = map.get(numType);
        newMap.put(numType,jsonObject);
        return newMap;
    }

    /**
     * 组装钢筋混凝土计算数据,每次返回一个建筑物序号的数据
     * @return
     */
    private List<Map> calculationParameters(List<Map> mapList,String numType,String structureType,String id,String versionId){
        List<Map> newMapList = new ArrayList<>();
        List<RcpExcelSheet1Vo> sheet1Data = (List<RcpExcelSheet1Vo>) mapList.get(0).get(numType);
        sheet1Data.forEach(item -> {
            if(structureType.equals("钢筋混凝土框架结构")){
                item.setStructureType1("框架结构");
            }else if(structureType.equals("钢筋混凝土-框架结构")){
                item.setStructureType1("框架结构");
            }else if(structureType.equals("钢筋混凝土-框架剪力墙结构")){
                item.setStructureType1("框架-剪力墙结构");
            }else if(structureType.equals("钢筋混凝土-剪力墙结构")){
                item.setStructureType1("剪力墙结构");
            }
            item.setTableId(id);
            item.setVersionId(versionId);
            item.setYears(handleYear(item.getYears()));
        });
        HashMap<String, Object> sheet1Map = new HashMap<>();
        sheet1Map.put(numType,sheet1Data);

        List<RcpExcelSheet2Vo> sheet2Data = (List<RcpExcelSheet2Vo>) mapList.get(1).get(numType);
        HashMap<String, Object> sheet2Map = new HashMap<>();
        sheet2Map.put(numType,sheet2Data);

        List<RcpExcelSheet3Vo> sheet3Data = (List<RcpExcelSheet3Vo>) mapList.get(2).get(numType);
        HashMap<String, Object> sheet3Map = new HashMap<>();
        sheet3Map.put(numType,sheet3Data);

        List<RcpExcelSheet4Vo> sheet4Data = (List<RcpExcelSheet4Vo>) mapList.get(3).get(numType);
        HashMap<String, Object> sheet4Map = new HashMap<>();
        sheet4Map.put(numType,sheet4Data);

        newMapList.add(sheet1Map);
        newMapList.add(sheet2Map);
        newMapList.add(sheet3Map);
        newMapList.add(sheet4Map);
        return newMapList;
    }


    private SmxBaseStationEntity baseStationToEntity(ImportBaseStationVo data, String versionId, String id, List<String> list) {
        SmxBaseStationEntity entity = new SmxBaseStationEntity();
        BeanUtils.copyProperties(data, entity);
        entity.setId(UUIDGenerator.getUUID());
        entity.setTableId(id);
        entity.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        entity.setCreateUser(PlatformSessionContext.getUserID());
        entity.setVersionId(versionId);
        entity.setDelFlag("0");
        if (PlatformObjectUtils.isNotEmpty(list) && list.size() == 5) {
            entity.setDisasterRate6State(list.get(0));
            entity.setDisasterRate7State(list.get(1));
            entity.setDisasterRate8State(list.get(2));
            entity.setDisasterRate9State(list.get(3));
            entity.setDisasterRate10State(list.get(4));
        }
        return entity;
    }


    private SmxGasStoreEntity gasStoreToEntity(ImportGasVo data, String versionId, String id, List<String> list) {
        SmxGasStoreEntity entity = new SmxGasStoreEntity();
        BeanUtils.copyProperties(data, entity);
        entity.setId(UUIDGenerator.getUUID());
        entity.setTableId(id);
        entity.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        entity.setCreateUser(PlatformSessionContext.getUserID());
        entity.setVersionId(versionId);
        entity.setDelFlag("0");
        if (PlatformObjectUtils.isNotEmpty(list) && list.size() == 5) {
            entity.setDisasterRate6State(list.get(0));
            entity.setDisasterRate7State(list.get(1));
            entity.setDisasterRate8State(list.get(2));
            entity.setDisasterRate9State(list.get(3));
            entity.setDisasterRate10State(list.get(4));
        }
        return entity;
    }

    private SmxPowerhouseEntity powerhouseToEntity(ImportPowerhouseVo data, String versionId, String id, List<String> list) {
        SmxPowerhouseEntity entity = new SmxPowerhouseEntity();
        BeanUtils.copyProperties(data, entity);
        entity.setId(UUIDGenerator.getUUID());
        entity.setTableId(id);
        entity.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        entity.setCreateUser(PlatformSessionContext.getUserID());
        entity.setVersionId(versionId);
        entity.setDelFlag("0");
        if (PlatformObjectUtils.isNotEmpty(list) && list.size() == 5) {
            entity.setDisasterRate6State(list.get(0));
            entity.setDisasterRate7State(list.get(1));
            entity.setDisasterRate8State(list.get(2));
            entity.setDisasterRate9State(list.get(3));
            entity.setDisasterRate10State(list.get(4));
        }
        return entity;
    }

    private void saveMainTable(String versionId, String businessObject, String id) {
        SmxMainTableEntity mainEntity = new SmxMainTableEntity();
        mainEntity.setId(id);
        mainEntity.setCalculationStatus(1);
        mainEntity.setBusinessObject(businessObject);
        mainEntity.setCreateUser(PlatformSessionContext.getUserID());
        mainEntity.setVersionId(versionId);
        mainTableUtils.saveMainTable(mainEntity);
    }

    private String saveVersionInfo(ImportHubBuildingParam param, String fileName) {
        SmxVersionEntity entity = new SmxVersionEntity();
        entity.setId(UUIDGenerator.getUUID());
        entity.setVersionCode(versionCodeUtils.getVersionCode(param.getType()));
        entity.setProvince(param.getProvince());
        entity.setCity(param.getCity());
        entity.setCounty(param.getCounty());
        entity.setFileIds(param.getFileId());
        entity.setFileName(fileName);
        entity.setVersionStatus(1);
        entity.setCreateUser(PlatformSessionContext.getUserID());
        entity.setCreateUserName(getUserName().getUserName());
        entity.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        entity.setDelFlag("0");
        entity.setType(param.getType());
        lifelineEngineeringRepository.saveSmxVersion(entity);
        return entity.getId();
    }

    private String updateVersionInfo(ImportHubBuildingParam param, String fileName) {
        SmxVersionEntity entity = new SmxVersionEntity();
        entity.setFileName(fileName);
        entity.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        entity.setUpdateUser(PlatformSessionContext.getUserID());
        entity.setId(param.getId());
        entity.setFileIds(param.getFileId());
        entity.setVersionStatus(1);
        lifelineEngineeringRepository.updateSmxVersion(entity);
        return entity.getId();
    }

    public SUser getUserName() {
        String user = userService.getSUser(PlatformSessionContext.getUserID());
        return CreateGson.createGson().fromJson(user, SUser.class);
    }

    private RestResponse steelConcreteCalculation(List<Map> mapList) {
        ArrayList<String> list = new ArrayList<>();
        //柱参数
        Map<String, List> map0 = mapList.get(0);
        //梁参数
        Map<String, List> map1 = mapList.get(1);
        //剪力墙参数
        Map<String, List> map2 = mapList.get(2);
        //填充墙参数
        Map<String, List> map3 = mapList.get(3);
        //将同一个建筑的参数放到一个list<list>中。
        for (Map.Entry<String, List> entry : map0.entrySet()) {
            String key = entry.getKey();
            ArrayList<List> perList = new ArrayList<>();
            perList.add(0, map0.get(key));
            perList.add(1, map1.get(key));
            if(PlatformObjectUtils.isNotEmpty(map2)){
                perList.add(2,map2.get(entry.getKey()));
            }else {
                perList.add(2,null);
            }
            if(PlatformObjectUtils.isNotEmpty(map3)){
                perList.add(3,map3.get(entry.getKey()));
            }else {
                perList.add(3,null);
            }
            //计算
            try {
                RestResponse calculate = srcAnalyseService.calculate(perList);
                if(calculate.getCode() == 200){
                    Map<String, List> result = (Map<String, List>) calculate.getData();
                    if (PlatformObjectUtils.isNotEmpty(result)) {
                        List<CztCrsMatrixCalResult> matrixResultList = (List<CztCrsMatrixCalResult>) result.get(FxfzConstants.matrixResult);
                        if(PlatformObjectUtils.isNotEmpty(matrixResultList)){
                            list = getConclusion(matrixResultList);
                        }
                    }
                }else {
                    return RestResponse.fail(calculate.getMessage());
                }
            } catch (Exception e) {
                log.error("error:{}", e.getMessage(), e);
            }
        }
        return RestResponse.succeed(list);
    }

    private SmxWaterRoomEntity waterRoomToEntity(ImportWpRoomVo vo, String versionId, String id, List<String> list) {
        SmxWaterRoomEntity entity = new SmxWaterRoomEntity();
        BeanUtils.copyProperties(vo, entity);
        entity.setVersionId(versionId);
        entity.setTableId(id);
        entity.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        entity.setCreateUser(PlatformSessionContext.getUserID());
        entity.setId(UUIDGenerator.getUUID());
        entity.setDelFlag("0");
        if (PlatformObjectUtils.isNotEmpty(list) && list.size() == 5) {
            entity.setDisasterRate6State(list.get(0));
            entity.setDisasterRate7State(list.get(1));
            entity.setDisasterRate8State(list.get(2));
            entity.setDisasterRate9State(list.get(3));
            entity.setDisasterRate10State(list.get(4));
        }
        return entity;
    }

    private ArrayList<String> getConclusion(List<CztCrsMatrixCalResult> matrixCalResults) {
        HashMap<String, String> map = new HashMap<>();
        ArrayList<String> conclusionList = new ArrayList<>();
        // 根据烈度分组，并统计每个分组中破坏程度的出现次数
        Map<String, Map<String, Long>> count = matrixCalResults.stream()
                .collect(Collectors.groupingBy(
                        CztCrsMatrixCalResult::getSi,
                        Collectors.groupingBy(CztCrsMatrixCalResult::getDamageCondition, Collectors.counting())
                ));

        count.forEach((intensity, damageCountMap) -> {
            Optional<Map.Entry<String, Long>> maxEntry = damageCountMap.entrySet().stream()
                    .max(Map.Entry.comparingByValue());
            if (maxEntry.isPresent()) {
                Map.Entry<String, Long> entry = maxEntry.get();
                map.put(intensity,entry.getKey());
            }
        });
        conclusionList.add(map.get("6度"));
        conclusionList.add(map.get("7度"));
        conclusionList.add(map.get("8度"));
        conclusionList.add(map.get("9度"));
        conclusionList.add(map.get("10度"));
        return conclusionList;
    }

    private RestResponse brickConcreteCalculation(InputStream inputStream) {
        String userID = PlatformSessionContext.getUserID();
        String user = userService.getSUser(userID);
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        ExcelReader reader = ExcelUtil.getReader(inputStream, 1);
        List<List<Object>> read = reader.read(5, reader.getRowCount());
        List<Object> title = reader.readRow(3);
        String titleName = "[建筑物序号, 楼层序号, 用途, 用途, 省份, 市, 区/县级, 设防情况, 建设年份, 楼层对应的砂浆强度(M), 外墙厚度, 内墙厚度, 层宽, 层长, 总楼层数, 墙体截面积, （楼层）建筑面积, 结构无明显质量问题, 平立面规则, 建筑抗震设计规范, 楼屋盖类型, 承重墙间距]";
        if (!titleName.equals(title.toString())) {
            return RestResponse.fail("导入失败，请检查表头是否改动");
        }
        if (read.size() < 1) {
            return RestResponse.fail("导入失败，表格中无数据");
        }
        //数据校验
        RestResponse rs = pobParameterVerification(read.size(), read);
        if (rs.getCode() != 200) {
            return RestResponse.fail(rs.getMessage());
        }
        /**
         * key:建筑编号
         * values:
         *      jsonObject:
         *          cbcbInfoEntity 建筑信息（楼）
         *          detailList  楼的详情（楼层）
         */
        Map<String, JSONObject> map = new HashMap<>();
        JSONObject jsonObject = null;
        List<CbcbDetailEntity> detailList = null;
        for (List<Object> objects : read) {
            String buildingNumber = objects.get(0).toString();//建筑编号,同一栋楼编号相同，不同的楼编号不同
            CbcbInfoEntity cbcbInfoEntity = null;
            //同一栋楼的信息放到一起
            if (map.containsKey(buildingNumber)) {
                jsonObject = map.get(buildingNumber);
                cbcbInfoEntity = JSON.parseObject(JSON.toJSONString(jsonObject.getJSONObject("cbcbInfoEntity")),
                        CbcbInfoEntity.class);
                detailList = JSON.parseArray(JSON.toJSONString(jsonObject.getJSONArray("detailList")), CbcbDetailEntity.class);
            } else {
                jsonObject = new JSONObject();
                cbcbInfoEntity = new CbcbInfoEntity();
                cbcbInfoEntity.setCbcbiId(UUIDGenerator.getUUID());
                cbcbInfoEntity.setBuildingNumber(objects.get(0).toString());
                cbcbInfoEntity.setPurpose(objects.get(2).toString());
                cbcbInfoEntity.setPurpose1(objects.get(3).toString());
                cbcbInfoEntity.setProvince(objects.get(4).toString());
                cbcbInfoEntity.setCity(objects.get(5).toString());
                cbcbInfoEntity.setCounty(objects.get(6).toString());
                cbcbInfoEntity.setStructureType("砌体结构");
                cbcbInfoEntity.setStructureType1("砖混结构");
                cbcbInfoEntity.setFortification(objects.get(7).toString());
                String years = handleYear(objects.get(8).toString());
                cbcbInfoEntity.setYears(years);
                cbcbInfoEntity.setOutThickness(Double.parseDouble(objects.get(9).toString()));
                cbcbInfoEntity.setInnerThickness(Double.parseDouble(objects.get(11).toString()));
                cbcbInfoEntity.setTotalFloor(Integer.parseInt(objects.get(14).toString()));
                if (cbcbInfoEntity.getTotalFloor().compareTo(3) < 1) {
                    cbcbInfoEntity.setFloor("1-3层");
                } else {
                    cbcbInfoEntity.setFloor("4-8层");
                }
                cbcbInfoEntity.setCiType1("结构无明显质量问题");
                if ("是".equals(objects.get(17).toString())) {
                    cbcbInfoEntity.setCiType1Value(1);
                } else {
                    cbcbInfoEntity.setCiType1Value(2);
                }
                cbcbInfoEntity.setCiType2("平立面规则");
                if ("规则".equals(objects.get(18).toString())) {
                    cbcbInfoEntity.setCiType2Value(1);
                } else {
                    cbcbInfoEntity.setCiType2Value(2);
                }
                cbcbInfoEntity.setCiType3("建筑抗震设计规范");
                cbcbInfoEntity.setCiType3Value(BuildingSeismicResistanceEnum.getByName(objects.get(19).toString()));
                cbcbInfoEntity.setCiType4("楼屋盖类型");
                cbcbInfoEntity.setCiType4Value(BuildingRoofEnum.getByName1(objects.get(20).toString()));
                cbcbInfoEntity.setSpacing(Double.valueOf(objects.get(21).toString()));
                cbcbInfoEntity.setCreateUser(userID);
                cbcbInfoEntity.setUserName(sUser.getUserName());
                cbcbInfoEntity.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
                cbcbInfoEntity.setDelFlag(YNEnum.N.toString());
                cbcbInfoEntity.setCalculateOrNot("0");
                cbcbInfoEntity.setDataType(FxfzConstants.CZT_ZHJG_INFO);
                cbcbInfoEntity.setBasicLibrary("0");
                String number = generationNumberUtil.getCityInitials(cbcbInfoEntity.getProvince()) + "-" +
                        generationNumberUtil.type(cbcbInfoEntity.getStructureType(), cbcbInfoEntity.getStructureType1()) + "-" +
                        generationNumberUtil.getFs(cbcbInfoEntity.getFortification()) + "-" + this.getNumber(RedisKeyConstants.CZT_ZHJG_KEY);
                cbcbInfoEntity.setNumber(number);
                jsonObject.put("cbcbInfoEntity", cbcbInfoEntity);
                detailList = new ArrayList<>();
            }
            CbcbDetailEntity cbcbDetailEntity = new CbcbDetailEntity();
            cbcbDetailEntity.setCbcbdId(UUIDGenerator.getUUID());
            cbcbDetailEntity.setFloorNumber(Integer.valueOf(objects.get(1).toString()));
            cbcbDetailEntity.setMortar(Double.parseDouble(objects.get(9).toString()));
            cbcbDetailEntity.setWidth(Double.parseDouble(objects.get(12).toString()));
            cbcbDetailEntity.setLength(Double.parseDouble(objects.get(13).toString()));
            cbcbDetailEntity.setSectionArea(new BigDecimal(objects.get(15).toString()));
            cbcbDetailEntity.setBuildArea(new BigDecimal(objects.get(16).toString()));
            cbcbDetailEntity.setCbcbiId(cbcbInfoEntity.getCbcbiId());
            cbcbDetailEntity.setCreateUser(userID);
            cbcbDetailEntity.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
            cbcbDetailEntity.setDelFlag(YNEnum.N.toString());
            detailList.add(cbcbDetailEntity);
            jsonObject.put("detailList", detailList);
            map.put(buildingNumber, jsonObject);
        }
        return RestResponse.succeed(map);
    }

    private RestResponse pobParameterVerification(int size, List<List<Object>> data) {
        //"[序号, 建筑编号, 楼层序号, 用途, 用途, 省份, 市, 区/县级, 设防情况, 建造年代, 楼层对应的砂浆强度(M), 外墙厚度, 内墙厚度," +
        //" 层宽, 层长, 总楼层数, 墙体截面积, （楼层）建筑面积, 结构无明显质量问题, 平立面规则, 建筑抗震设计规范, 楼屋盖类型, 承重墙间距]";
        for (int i = 0; i < size; i++) {
            List<Object> objects = data.get(i);
            if (objects.size() != 22) {
                return RestResponse.fail("第" + (i + 5) + "行的数据存在空值！");
            }
            if (PlatformObjectUtils.isEmpty(objects.get(0) + ""))
                return RestResponse.fail("第" + (i + 5) + "行的{建筑编号}不能为空！");
            if (PlatformObjectUtils.isEmpty(objects.get(1) + ""))
                return RestResponse.fail("第" + (i + 5) + "行的{楼层序号}不能为空！");
            if (PlatformObjectUtils.isEmpty(objects.get(2) + ""))
                return RestResponse.fail("第" + (i + 5) + "行的{用途}不能为空！");
            if (PlatformObjectUtils.isEmpty(objects.get(3) + ""))
                return RestResponse.fail("第" + (i + 5) + "行的{用途}不能为空！");
            if (PlatformObjectUtils.isEmpty(objects.get(4) + ""))
                return RestResponse.fail("第" + (i + 5) + "行的{省份}不能为空！");
            if (PlatformObjectUtils.isEmpty(objects.get(5) + ""))
                return RestResponse.fail("第" + (i + 5) + "行的{市}不能为空！");
            if (PlatformObjectUtils.isEmpty(objects.get(6) + ""))
                return RestResponse.fail("第" + (i + 5) + "行的{区/县级}不能为空！");
            if (PlatformObjectUtils.isEmpty(objects.get(7) + ""))
                return RestResponse.fail("第" + (i + 5) + "行的{设防情况}不能为空！");
            if (PlatformObjectUtils.isEmpty(objects.get(8) + ""))
                return RestResponse.fail("第" + (i + 5) + "行的{建造年代}不能为空！");
            if (PlatformObjectUtils.isEmpty(objects.get(9) + ""))
                return RestResponse.fail("第" + (i + 5) + "行的{楼层对应的砂浆强度(M)}不能为空！");
            if (PlatformObjectUtils.isEmpty(objects.get(10) + ""))
                return RestResponse.fail("第" + (i + 5) + "行的{外墙厚度}不能为空！");
            if (PlatformObjectUtils.isEmpty(objects.get(11) + ""))
                return RestResponse.fail("第" + (i + 5) + "行的{内墙厚度}不能为空！");
            if (PlatformObjectUtils.isEmpty(objects.get(12) + ""))
                return RestResponse.fail("第" + (i + 5) + "行的{层宽}不能为空！");
            if (PlatformObjectUtils.isEmpty(objects.get(13) + ""))
                return RestResponse.fail("第" + (i + 5) + "行的{层长}不能为空！");
            if (PlatformObjectUtils.isEmpty(objects.get(14) + ""))
                return RestResponse.fail("第" + (i + 5) + "行的{总楼层数}不能为空！");
            if (PlatformObjectUtils.isEmpty(objects.get(15) + ""))
                return RestResponse.fail("第" + (i + 5) + "行的{墙体截面积}不能为空！");
            if (PlatformObjectUtils.isEmpty(objects.get(16) + ""))
                return RestResponse.fail("第" + (i + 5) + "行的{（楼层）建筑面积}不能为空！");
            if (PlatformObjectUtils.isEmpty(objects.get(17) + ""))
                return RestResponse.fail("第" + (i + 5) + "行的{结构无明显质量问题}不能为空！");
            if (PlatformObjectUtils.isEmpty(objects.get(18) + ""))
                return RestResponse.fail("第" + (i + 5) + "行的{平立面规则}不能为空！");
            if (PlatformObjectUtils.isEmpty(objects.get(19) + ""))
                return RestResponse.fail("第" + (i + 5) + "行的{建筑抗震设计规范}不能为空！");
            if (PlatformObjectUtils.isEmpty(objects.get(20) + ""))
                return RestResponse.fail("第" + (i + 5) + "行的{楼屋盖类型}不能为空！");
            if (PlatformObjectUtils.isEmpty(objects.get(21) + ""))
                return RestResponse.fail("第" + (i + 5) + "行的{承重墙间距}不能为空！");
        }
        return RestResponse.succeed();
    }

    private String getNumber(String key) {
        return generationNumberUtil.getGenerationNumber(key);
    }
}
